package es.upv.epsa.mobweb.moneyback;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.databind.ObjectMapper;

import es.upv.epsa.mobweb.moneyback.adapters.ItemsListItemAdapter;
import es.upv.epsa.mobweb.moneyback.database.Contact;
import es.upv.epsa.mobweb.moneyback.database.Item;
import es.upv.epsa.mobweb.moneyback.json.JSONParser;

public class AccountActivity extends Activity {
	
	private Button		btnSave;
	private Button 		btnRemind;
	private Button 		btnForgive;
	private Button 		btnOffset;
	private TextView	txtAccount;
	private EditText	editAccount;
	private TextView	txtFriend;
	private TextView	txtAmount;
	private Button		btnAdd;
	private ListView	list;
	private TextView	txtVacia;
	
	private String 		account_name;
	private int			friend_id;
	private int			accountid;
	private String		server_url;
	private JSONParser 	jsonParser;
	
	private ObjectMapper  		mapper 	= new ObjectMapper();
	private ArrayList<Item> 	items 	= new ArrayList<Item>();
	private ArrayList<String[]> allItems= new ArrayList<String[]>();
	
	private MainApplication app;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.account);
		
		account_name= getIntent().getExtras().getString("account_name");
		friend_id	= Integer.valueOf(getIntent().getExtras().getString("friend_id"));
		
		app = (MainApplication) getApplication();
		
		if(getIntent().getExtras().getString("accountid") != null)
			accountid	= Integer.valueOf(getIntent().getExtras().getString("accountid"));
		
		jsonParser = new JSONParser();
		
		setWidgets();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.account, menu);
		return true;
	}
	
	@Override
	protected void onResume(){
		super.onResume();
		
		getData();
	}
	
	private void setWidgets(){
		server_url	= getResources().getString(R.string.server_url);
		
		btnSave		= (Button)		findViewById(R.id.btnSave);
		btnRemind 	= (Button) 		findViewById(R.id.btnRemind);
		btnForgive 	= (Button) 		findViewById(R.id.btnForgive);
		btnOffset 	= (Button) 		findViewById(R.id.btnOffset);
		txtAccount	= (TextView) 	findViewById(R.id.txtAccount);
		editAccount	= (EditText)	findViewById(R.id.editAccount);
		txtFriend	= (TextView) 	findViewById(R.id.txtFriend);
		txtAmount	= (TextView)	findViewById(R.id.txtAmount);
		btnAdd		= (Button)		findViewById(R.id.btnAdd);
		list		= (ListView)	findViewById(R.id.list);
		txtVacia	= (TextView)	findViewById(R.id.txtVacia);
		
		if(account_name == null){
			txtAccount.setVisibility(View.GONE);
			editAccount.setVisibility(View.VISIBLE);
			
			btnSave.setVisibility(View.VISIBLE);
			btnRemind.setVisibility(View.GONE);
			btnForgive.setVisibility(View.GONE);
			btnOffset.setVisibility(View.GONE);
			btnAdd.setVisibility(View.GONE);
		}
		
		btnSave.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View view) {
				saveAccount();
			}
			
		});
		
		btnRemind.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View view) {
				Toast.makeText(getApplicationContext(), "Sorry, push notifications not enabled yet...", Toast.LENGTH_LONG).show();
			}
			
		});
		
		btnForgive.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View view) {
				new AlertDialog.Builder(AccountActivity.this)
				.setIcon(android.R.drawable.ic_dialog_alert)
				.setTitle("Forgive Account")
				.setMessage("Are you sure you want to forgive this account?")
				.setPositiveButton("Yes", new DialogInterface.OnClickListener(){
					@Override
					public void onClick(DialogInterface dialog, int which) {
						deleteAccount();
					}

				})
				.setNegativeButton("No", null)
				.show();
			}
			
		});
		
		btnOffset.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View view) {
				
			}
			
		});
		
		txtAccount.setText(account_name);
		
		btnAdd.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View arg0) {
				Intent intent = new Intent();
				intent.setClass(getApplicationContext(), ItemActivity.class);
				intent.putExtra("friend", String.valueOf(friend_id));
				intent.putExtra("accountid", String.valueOf(accountid));
				
				startActivity(intent);
			}
			
		});
		
		list.setOnItemClickListener(new OnItemClickListener(){

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				String[] data = (String[]) list.getItemAtPosition(position);
				
				Intent intent = new Intent();
				intent.setClass(getApplicationContext(), ItemActivity.class);
				intent.putExtra("id", data[2]);
				intent.putExtra("friendId", String.valueOf(friend_id));
				intent.putExtra("accountid", String.valueOf(accountid));
				startActivity(intent);
			}
			
		});
		
		getData();
	}
	
	private void deleteAccount(){
		JsonFactory 			jfactory 	= new JsonFactory();
		ByteArrayOutputStream 	bout 		= new ByteArrayOutputStream();
		JsonGenerator 			jGenerator;

		try {
			jGenerator = jfactory.createJsonGenerator(new OutputStreamWriter(bout, "UTF-8"));
			jGenerator.writeStartObject();

			jGenerator.writeNumberField("action", 3);
			jGenerator.writeNumberField("id", accountid);

			jGenerator.writeEndObject();
			jGenerator.close();

			new SendJSON(getResources().getString(R.string.accounts_url), bout.toString(), 2).execute();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	private void saveAccount(){
		JsonFactory 			jfactory 	= new JsonFactory();
		ByteArrayOutputStream 	bout 		= new ByteArrayOutputStream();
		JsonGenerator 			jGenerator;

		try {
			jGenerator = jfactory.createJsonGenerator(new OutputStreamWriter(bout, "UTF-8"));
			jGenerator.writeStartObject();

			jGenerator.writeNumberField("action", 1);
			jGenerator.writeStringField("name", editAccount.getText().toString());
			jGenerator.writeNumberField("owner", app.getUser().getId());
			jGenerator.writeNumberField("friend", friend_id);
			jGenerator.writeNumberField("shared", 0);
			jGenerator.writeNumberField("daily_interest", 0.0);

			jGenerator.writeEndObject();
			jGenerator.close();

			new SendJSON(getResources().getString(R.string.accounts_url), bout.toString(), 2).execute();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	private void getItems(){
		JsonFactory 			jfactory 	= new JsonFactory();
		ByteArrayOutputStream 	bout 		= new ByteArrayOutputStream();
		JsonGenerator 			jGenerator;

		try {
			jGenerator = jfactory.createJsonGenerator(new OutputStreamWriter(bout, "UTF-8"));
			jGenerator.writeStartObject();

			jGenerator.writeNumberField("action", 4);
			jGenerator.writeNumberField("accountid", accountid);

			jGenerator.writeEndObject();
			jGenerator.close();

			new SendJSON(getResources().getString(R.string.items_url), bout.toString(), 1).execute();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	private void getData(){
		JsonFactory 			jfactory 	= new JsonFactory();
		ByteArrayOutputStream 	bout 		= new ByteArrayOutputStream();
		JsonGenerator 			jGenerator;

		try {
			jGenerator = jfactory.createJsonGenerator(new OutputStreamWriter(bout, "UTF-8"));
			jGenerator.writeStartObject();

			jGenerator.writeNumberField("action", 3);
			jGenerator.writeNumberField("id", friend_id);

			jGenerator.writeEndObject();
			jGenerator.close();

			new SendJSON(getResources().getString(R.string.contacts_url), bout.toString(), 0).execute();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	private class SendJSON extends AsyncTask<Void, Void, Void>{
		String 			json 	= "";
		int		 		parse 	= 0;
		String 			data 	= "";
		String 			file	=  getResources().getString(R.string.contacts_url);
		ProgressDialog 	dialog;
		
		public SendJSON(String file, String json, int parse){
			this.json 	= json;
			this.parse 	= parse;
			this.file 	= file;
		}
		
		@Override
		protected Void doInBackground(Void... arg0) {
			data = jsonParser.sendJSON(server_url + file, json);
			
			return null;
		}
		
		@Override
		protected void onPreExecute(){
			dialog = ProgressDialog.show(AccountActivity.this, "", "Loading data...", true);
			dialog.setCancelable(false);
			dialog.setOnCancelListener(new OnCancelListener(){

				@Override
				public void onCancel(DialogInterface dialog) {

				}
				
			});
		}
		
		@Override
		protected void onPostExecute(Void result){
			if(parse == 0){
				parseJSONFriend(data);
			}else if(parse == 1){
				parseJSONItems(data);
			}else{
				dialog.dismiss();
				
				Intent intent = new Intent();
				intent.setClass(getApplicationContext(), AccountsListActivity.class);
				
				startActivity(intent);
				finish();
			}
			
			dialog.dismiss();
		}
	}
	
	private void parseJSONFriend(String json){
		try {
			JsonFactory jfactory = new JsonFactory();
			JsonParser jparser = jfactory.createJsonParser(json);

			//jparser.nextToken();
			while(jparser.nextToken() == JsonToken.START_OBJECT){
				Contact c = new Contact();
				c = mapper.readValue(jparser, Contact.class);
				txtFriend.setText(c.getName());
			}

			jparser.close();
			
			getItems();
		} catch (JsonParseException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	private void parseJSONItems(String json){
		try {
			float amount = 0.0f;
			JsonFactory jfactory = new JsonFactory();
			JsonParser jparser = jfactory.createJsonParser(json);

			allItems.clear();
			jparser.nextToken();
			while(jparser.nextToken() == JsonToken.START_OBJECT){
				Item i = new Item();
				i = mapper.readValue(jparser, Item.class);
				
				items.add(i);
				amount += i.getAmount();
				
				allItems.add(new String[]{i.getName(), String.valueOf(i.getAmount()), String.valueOf(i.getId())});
			}

			jparser.close();
			
			if(allItems.size() == 0){
				list.setVisibility(View.GONE);
				txtVacia.setVisibility(View.VISIBLE);
			}
			
			txtAmount.setText(String.valueOf(amount) + "€");
			ItemsListItemAdapter adapter = new ItemsListItemAdapter(this, allItems);
			list.setAdapter(adapter);
		} catch (JsonParseException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
